using mozhi.smarterp.Gateway.Internal.Middlewares.authorization;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Serilog.Events;
using Serilog;
using mozhi.smarterp.Gateway.Internal.DelegationHandlers;

public class Program
{
    public async static Task<int> Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
#if DEBUG
            .MinimumLevel.Debug()
#else
            .MinimumLevel.Information()
#endif
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
            .Enrich.FromLogContext()
            .WriteTo.Async(c => c.File($"Logs/logs-{DateTime.Now.ToString("yyyy-MM-dd")}.txt"))
            .WriteTo.Async(c => c.Console())
            .CreateLogger();
        try
        {
            Log.Information("Starting mozhi.smarterp.Getaway.Internal.");

            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddHttpClient();

            builder.Configuration.SetBasePath(Environment.CurrentDirectory)
                .AddJsonFile("appsettings.json")
                .AddJsonFile("ocelot.json");

            builder.Host.UseSerilog();

            builder.Services.AddOcelot();

            //builder.Services.AddCors(options =>
            //{
            //    var corsOrigins = builder.Configuration["CorsOrigins"].ToString();

            //    options.AddDefaultPolicy(policy =>
            //    {
            //        policy
            //            .WithOrigins(
            //                corsOrigins
            //                    .Split(",", StringSplitOptions.RemoveEmptyEntries)
            //                    .Select(o => o)
            //                    .ToArray()
            //            )
            //            .AllowAnyHeader()
            //            .AllowAnyMethod()
            //            .AllowCredentials();
            //    });
            //});

            var app = builder.Build();

            //app.UseCors();
            app.UseMozhiAuthorization();

            await app.UseOcelot();

            app.Run();
            return 0;
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly!");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}

